package com.zis.platform.common.authentication.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zis.platform.common.authentication.UserToken;
import com.zis.platform.common.util.CacheCoreUtil;
import com.zis.platform.core.entity.SysEntity;
import com.zis.util.URLHelper;

/**
 * 
 * <b>说明：</b>url越权访问拦截<br>
 * 如果拦截成功则设置相应状态值为403并由系统设置的403进行视图展示
 * 
 * @ClassName: ShiroUrlInterceptor
 * @author zhaohaitao(2543)
 * @date 2015-7-9 下午6:14:20
 * 
 */
public class ShiroUrlInterceptor implements HandlerInterceptor
{
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception
    {
    }
    
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
        throws Exception
    {
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2)
        throws Exception
    {
        SysEntity sysInfo = CacheCoreUtil.getSysInfo(request);
        UserToken userToken = (UserToken)SecurityUtils.getSubject().getPrincipal();
        String uri = URLHelper.getURI(request);
        if (userToken != null && !uri.equals(sysInfo.getLoginUrl()) && !uri.equals(sysInfo.getLogoutUrl())
            && !uri.equals(sysInfo.getWelcomeUrl()))
        {
            boolean permitted = SecurityUtils.getSubject().isPermitted(uri);
            if (!permitted)
            {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        return true;
    }
}
